package echo.netty.hartbeat;

import echo.netty.TestProtocol.MessageCodec;
import echo.netty.TestProtocol.PingMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author： zhangnan
 * @date： 2025/5/13 14:48
 * @description： 测试心跳 netty 客户端
 * 使用 IdleStateHandler 和 ChannelDuplexHandler  来处理 写空闲 事件
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
public class TestHartbeatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            ChannelFuture channelFuture = new Bootstrap()
                    .channel(NioSocketChannel.class)
                    .group(group)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MessageCodec());
                            // 添加 IdleStatehandler
                            // 3S 内如果没有向服务器写数据，会触发一个 IdleState#WRITER_IDLE 事件
                            pipeline.addLast(new IdleStateHandler(0, 2, 0));
                            // 处理 写空闲事件
                            pipeline.addLast(new ChannelDuplexHandler() {
                                @Override
                                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                    IdleStateEvent event = (IdleStateEvent) evt;
                                    if (event.state() == IdleState.WRITER_IDLE){ // 触发读空闲事件
                                        log.debug("3S 没有写数据了，发送一个心跳包");
                                        ctx.writeAndFlush(new PingMessage());
                                    }
//                                    super.userEventTriggered(ctx, evt);
                                }
                            });
                            pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                        }
                    })
                    .connect(new InetSocketAddress("localhost", 8080));
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }

}
